import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutterdemo/0demo/provider/02my_demo/provider_data/common_data.dart';
import 'package:provider/provider.dart';

class TabViewWidget5 extends StatefulWidget {
  const TabViewWidget5({Key key}) : super(key: key);

  @override
  _TabViewWidget5State createState() => _TabViewWidget5State();
}

class _TabViewWidget5State extends State<TabViewWidget5> with AutomaticKeepAliveClientMixin {
  UserModel userModel;

//  @override
//  void initState() {
//    userModel = widget.userModel;
//    super.initState();
//  }
  @override
  Widget build(BuildContext context) {
    print("page 5 build");
    // 只有被监听的**引用地址**发生改变才会刷新
    userModel = context.select((CommonData commonData) => commonData.userModel);
    // 如果要监听model中的局部变量，使用getter才是局部变量的引用地址，否则无法感知
    int age = context.select((CommonData commonData) => commonData.userAge);
    String name = context.select((CommonData commonData) => commonData.userName);
    return Container(
      padding: EdgeInsets.all(20.w),
      child: Card(
        child: Column(
          children: <Widget>[
            Text(_getLatestUserInfo()),
            Text("age: $age"),
            Text("name: $name"),
            FlatButton(
              onPressed: _changeUserModel,
              child: Text("修改整个UserModel"),
            ),
            FlatButton(
              onPressed: _changeUserName,
              child: Text("修改UserModel.name"),
            ),
            FlatButton(
              onPressed: _changeUserAge,
              child: Text("修改UserModel.age"),
            )
          ],
        ),
      ),
    );
  }

  String _getLatestUserInfo() {
    return userModel == null ? "null" : userModel.toString();
  }

  void _changeUserModel() {
    context.read<CommonData>().changeUserModel();
  }

  void _changeUserName() {
    context.read<CommonData>().changeUsername("aaaaaaaaa");
  }

  void _changeUserAge() {
    context.read<CommonData>().changeUserAge(18);
  }

  @override
  void dispose() {
    print("5 dispose");
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}
